# -*- coding:utf-8 -*-
# Author:wencheng.zhao
p_list = {
"汽车类":[("宝马",10000),("奔驰",20000),("奥迪",30000),("宾利",40000)],
"服装":[("帽子",100),("衬衫",200),("裤子",300),("鞋子",40000)],
"宠物":[("猴子",10),("老鼠",20),("小狗",300),("小猫",30)],
"电器":[("风扇",300),("水壶",400),("空调",500),("冰箱",900)]
}
shop_car_file = open('p_list.txt','r')          #读取购物历史记录文件
shop_car = eval(shop_car_file.readline())
#print(shop_car)
shop_car_file.close()
# shop_car_now_file = open('p_list_now.txt','r')
# shop_car_now = eval(shop_car_now_file.readline())
# #print(shop_car)
# shop_car_now_file.close()
shop_car_now = []                               #定义购物车列表
shop_p_list = []                                #只存放商品列表用于判断是否已经购买过此商品
import json
import time

flag3 = int(1)      ##标记是否打印欢迎界面默认1为打印
flag4 = int(1)      ##标记是否提示注册用户名
flag5 = int(1)      ##标记是否打印第三个欢迎界面（充值功能时使用）
flag6 = int(1)      ##标记是否重新
structure = int(1)  #默认为1 不同模块值不相同
choice = 0
while True:
    #print(choice)
    ########structure为1进入欢迎和登录注册功能模块
    if structure == 1:
        if flag3 == 1:
            welcom_msg = '欢迎光临购物商城--首页'.center(60, '-')
            print(welcom_msg)
            show = '''
            1. 用户登录（已存在用户）
            2. 用户注册（新用户注册）
            3. 退出系统
                        '''
            print(show)                 ##打印首页内容
            choice = input('请选择数字 1 or 2:').strip()
        if choice.isdigit():                    ##判断输入是否为数字
            choice = int(choice)
            op_usename = open('username.txt', 'r')      #打开存放用户名密码的文件
            username_txt = eval(op_usename.readline())     #读取为字典模式
            op_usename.close()
            ######已存在用户登录功能
            if choice == 1:
                flag = int(1)    ##当用户登陆时标识是否打印获取用户名
                flag2 = int(1)
                try_num = int(0)    #用户名错误尝试的次数
                left_num = int(3)   #剩余可尝试的次数
                while True:
                    if flag == 1:
                        if flag2 == 1:
                            username_input = input("请输入用户名：").strip()
                        passwd_input = input("请输入密码：").strip()
                        if username_input in username_txt.keys():
                            if passwd_input == username_txt[username_input][0]:
                                print("\033[32m欢迎%s，登录成功\033[0m"%username_input)
                                structure = 2
                                break
                            else:
                                num = left_num - try_num
                                print("\033[31m密码错误剩余尝试次数为%d\033[0m"%(num))  #打印剩余可尝试次数
                                flag2 = int(2)
                                try_num += 1
                                if try_num == 4:
                                    print("\033[31m密码尝试次数已到请重新选择\033[0m")
                                    break
                        elif username_input not in username_txt.keys():
                            msg2 = '''
              用户名不存在，你可以:
              1.重新输入用户名密码
              2.跳转进入可注册界面
              其他键退出。。。。。
                            '''
                            print(msg2)          #当用户名不存在是寻问是否重新输入或者进入注册界面
                            second_choice = input("请选择：").strip()
                            if second_choice.isdigit():
                                second_choice = int(second_choice)
                                if second_choice == 1:
                                    continue
                                elif second_choice == 2:
                                    flag = int(2)
                                    break
                                else:
                                    exit("谢谢光临，再见！！")
                            else:
                                exit("谢谢光临，再见！！")
                    else:
                        break
            #####新用户注册功能##########
            elif choice == 2:
                if flag4 == 1:
                    username_input = input("请填写注册用户名：").strip()
                passwd_register1 = input("请输入密码").strip()
                passwd_register2 = input("请再次输入密码").strip()
                if username_input in username_txt.keys():            #判读将要注册的用户名是否存在
                    print("\033[31m用户已经存在请直接登陆\033[0m")
                    continue
                else:
                    if passwd_register1 == passwd_register2:
                        print("\033[32m恭喜注册成功！！\033[0m")
                        shop_car[username_input] = []           #注册成功后初始化购物历史记录文件
                        shop_car_str = json.dumps(shop_car)
                        shop_car_file_sec = open('p_list.txt','w')
                        shop_car_file_sec.write(shop_car_str)
                        shop_car_file_sec.close()
                        #
                        username_txt[username_input]=[passwd_register1,0] #将新注册的用吗密码以及余额写入文件默认余额为零
                        username_str = json.dumps(username_txt)
                        #json.dumps(username_txt,open('username.txt', 'w'))
                        op_usename = open('username.txt', 'w')
                        op_usename.write(username_str)
                        op_usename.close()
                        structure = 2
                    else:
                        print("\033[31m两次密码不同，请再确认次重新输入。\033[0m")     #注册时两次密码不这提示重新输入
                        choice = "2"
                        flag3 = 2
                        flag4 = 2
            elif choice == 3:
                exit('谢谢光临，再见！')

            else:
                print("\033[31m数字选择超出范围！！\033[0m")
        else:
            print("\033[31m选择有误请正确选择  请选择数字\033[0m")
            continue

        ###第二部分登陆成功后打印用户欢迎信息提示用户功能选择
    if structure == 2:
        if flag5 == 1:
            salary = int(username_txt[username_input][1])   #获取工资余额
            if username_input not in shop_car.keys():
                shop_car[username_input]=[]                 #如果用户没有购物记录则初始化下购物车列表
            msg_s = "亲爱的%s欢迎光临,卡内余额为%d" % (username_input,salary)
            print(msg_s.center(60,'-'))
            msg3 = '''
            1.立刻充值
            2.查看历史购物记录
            3.退出登陆
            [回车]任意键进入购买模式
                '''
            print(msg3)
            thr_choice =  input("请您选择：")
        if thr_choice.isdigit():
            thr_choice = int(thr_choice)
            if thr_choice == 1:
                #充值功能区
                add_salary = input("请输入充值金额(大于0的数字):")
                if add_salary.isdigit():
                    add_salary = int(add_salary)
                    if add_salary <= 0 :
                        flag5 = int(2)
                        thr_choice = "1"
                        print("\033[31m请输入大于0的数字，如下请重新输入：\033[0m")
                        continue
                    else:
                        salary = salary + add_salary     #总余额为老的余额加用户充值的余额
                        username_txt[username_input][1] = salary
                        #print(username_txt)
                        username_salary = json.dumps(username_txt)
                        #print(type(username_salary))
                        op_usename = open('username.txt', 'w')
                        op_usename.write(username_salary)
                        op_usename.close()
                        flag5 = 1
                        continue

                else:
                    print("\033[31m输入错误请输入数字。。\033[0m")
                    flag5 = int(2)
                    thr_choice = "1"
                    continue
            ####查看购物历史部分
            elif thr_choice == 2:
                #op_history = open('history.txt','r')
                history_file = open('p_list.txt', 'r')
                history_dic = eval(history_file.readline())   #将购物历史读入到历史字典中
                #print(history_dic[username_input])
                msg_h = "历史购物记录"
                print(msg_h.center(60, "*"))
                print("\033[34m所有历史商品   购买数量   消费总额      最后购买时间\033[0m")
                for p in history_dic[username_input]:
                    # print(p[0],'      ',p[1],'          ',p[2],'     ',p[3])
                    print("%s %10s %13s %25s" % (p[0], p[1], p[2], p[3],))
                    print("-".center(66,"-"))
                msg_e = "-END-"
                print(msg_e.center(66, '*'))
                print("")

            elif thr_choice == 3:
                structure = 1
                continue
        else:
            structure = 3

    #####显示购物列表选择购物商城
    if structure == 3:
        #print(p_list)
        pindex_list = list(p_list.keys())
        #print(pindex_list)
        for i in p_list:
            index_num = pindex_list.index(i) + 1  # 获取展示的编号（列表的inde+1）
            print(("%s.""%s") % (index_num, i))  # 展示
        userchoice = input("请选择商品种类(数字)，k[查看购物记录]b[返回用户登陆]，q[退出商城],c[进入充值界面]").strip()
        if userchoice.isdigit():
            userchoice = int(userchoice)
            if userchoice <= len(pindex_list) and userchoice != 0:
                for i in enumerate(p_list[pindex_list[userchoice-1]]):                     # 循环展示值('帽子', 100)
                    index_num_second = i[0] + 1
                    product = i[1][0]
                    price = i[1][1]
                    print(index_num_second,product,'........',price)
                userchoice_second = input("b[返回上一级]，q[退出登陆],请选择商品编号（输入数字）：").strip()
                if userchoice_second.isdigit():
                    userchoice_second = int(userchoice_second)
                    if  userchoice_second <= len(p_list[pindex_list[userchoice-1]])  and userchoice_second > 0:
                        #print (p_list[pindex_list[userchoice-1]])                #[('风扇', 300), ('热水器', 400), ('空调', 500), ('冰箱', 900)]
                        #购买商品
                        product = p_list[pindex_list[userchoice-1]][userchoice_second-1][0]  ##根据用户选择获取商品名称
                        price = p_list[pindex_list[userchoice-1]][userchoice_second-1][1]    ##根据用户选择获取商品单价
                        p_num = input("b[取消购买重新选择]q[退出系统],你选择的商品为 %s,单价为 %s元，请选择购买数量（数字）："%(product,price))
                        Now_time = time.time() + 28800
                        time_now = (time.gmtime(Now_time))
                        time_buy = time.strftime("%Y-%m-%d %X", time_now)    ##转换为购买时的时间

                        if p_num.isdigit():
                            p_num = int(p_num)
                            #print(len(p_list[pindex_list[userchoice-1]]))
                            if p_num >0:
                                price_a = price * p_num       ##总价格
                                #print(price_a)
                                if price_a <= salary:         ##判断是否可支付的起
                                    salary -= price_a
                                    #print(salary)
                                    #print(price_a)
                                    username_txt[username_input][1] = salary  ##将消费后的余额直接写入文件
                                    username_salary = json.dumps(username_txt)
                                    op_usename = open('username.txt', 'w')
                                    op_usename.write(username_salary)
                                    op_usename.close()
                                    # histor_list = [product,p_num,price,time_buy]
                                    gouw_list = [product,p_num,price_a,time_buy]
                                    if product in shop_p_list:          ##判读用户时否已经买过此商品了（判断同样商品只一行展示）
                                        for i in shop_car_now:
                                            #print(i)
                                            for k in i:
                                                #print(k)
                                                if k==product:
                                                    i[0]=product
                                                    i[1]+=p_num
                                                    i[2]+=price_a
                                                    i[3]=time_buy
                                                    #print(shop_car_now)     ##[['帽子', 2, 200, '购买时间']]

                                    else:
                                        shop_p_list.append(product)                 #只存放商品列表用于判断是否已经购买过此商品
                                        #print(shop_p_list)                         #['帽子']
                                        shop_car_now.append(gouw_list)
                                        #print(shop_car_now)        ##[['帽子', 2, 200, '购买时间']]
                                    print("\033[32m已经将 %s 加入购物车，本次消费 %s，剩余余额 %s\033[0m "%(product,price_a,salary))
                                    history_list=[product,p_num,price_a,time_buy] ##历史购物列表（用于追加到购物历史记录文件）
                                    #print(history_list)
                                    shop_car[username_input].append(history_list)

                                    shop_car_str = json.dumps(shop_car)
                                    shop_car_file_sec = open('p_list.txt', 'w')
                                    shop_car_file_sec.write(shop_car_str)
                                    shop_car_file_sec.close()
                                    #print(shop_car)


                                    continue
                                    #print(shop_car)          #{'1': [['猴子', 2, 20, '购买时间']]}
                                    #print("写入购物车，")

                                else:
                                    print("\033[31m你的余额不足以支付此商品，请选择其他商品或进入可充值界面。\033[0m")
                                    continue
                            else:
                                print("\033[31m输入不在范围内\033[0m")
                                continue

                        elif p_num == "q":
                            structure = 4
                            continue
                        elif p_num == "b":
                             continue
                        else:
                            print("\033[31m选择错误请重新选择。。。。\033[0m")
                            continue
                    else:
                        print("\033[31m数字超出范围，请重新选择\033[0m")

                elif userchoice_second == "b":
                    continue
                elif userchoice_second == "q":
                    structure = 4
                    continue
            else:
                print("\033[31m数字超出范围\033[0m")
                continue
        elif userchoice=="b":
            structure = int(1)
            continue
        elif userchoice == "q":
            structure = 4
            continue
        elif userchoice == "c":
            structure = int(2)
            continue
        elif userchoice == "k":          ###进入到查看购物车内容部分
            msg_p = "购物车内容"
            print(msg_p.center(60,"*"))
            print("\033[34m商品名称   购买数量   消费总额      购买时间\033[0m")
            for p in shop_car_now:
                #print(p[0],'      ',p[1],'          ',p[2],'     ',p[3])
                print("%s %10s %13s %25s"%(p[0],p[1],p[2],p[3],))
            msg_e = "-END-"
            print(msg_e.center(60,'*'))
            print("")

            #print(shop_car_now)
            continue
        else:
            print("\033[31m选择错误请重新选择。。。\033[0m")
            continue
    #####退出时展示购物车##########
    if structure == 4:
        msg_p = "如下商品购买成功"
        print(msg_p.center(60, "*"))
        print("\033[34m商品名称   购买数量   消费总额      购买时间\033[0m")
        for p in shop_car_now:
            # print(p[0],'      ',p[1],'          ',p[2],'     ',p[3])
            print("%s %10s %13s %25s" % (p[0], p[1], p[2], p[3],))
        msg_e = "-END-"
        print(msg_e.center(60, '*'))
        print("")
        exit("谢谢光临，再见")







